<template>
  <div class="app-container">

    <!-- 新增卡片区域 -->
    <el-row :gutter="20" class="mb-8 spacing-area">
      <!-- 系统时间卡片 -->
      <el-col :span="12">
        <el-card class="time-card">
          <div slot="header" class="clearfix">
            <span class="attendance-status">🕒 系统时间</span>
          </div>
          <div class="time-display">{{ currentTime }}</div>
        </el-card>
      </el-col>

      <!-- 考勤状态卡片 -->
      <el-col :span="12">
        <el-card class="attendance-card" v-if="signField.length > 0">
          <div slot="header" class="clearfix">
            <span class="attendance-status">
                📅 今日考勤状态
            </span>
            <span class="attendance-rule">
                | 打卡规则：
                <span class="rule-label">上班打卡</span>
                <span class="time-range">{{ getLabelByValue(0) }} - {{ getLabelByValue(1) }}</span>
                <span class="rule-label">下班打卡</span>
                <span class="time-range">{{ getLabelByValue(2) }} - {{ getLabelByValue(3) }}</span>
            </span>
          </div>
          <el-row :gutter="20">
            <!-- 上班打卡 -->
            <el-col :span="12">
              <div class="punch-card" :class="{ 'punched': clockInStatus }">
                <div class="status-icon">
                  <i :class="clockInStatus ? 'el-icon-success' : 'el-icon-time'"/>
                </div>
                <div class="time-info">
                  <div class="label">上班打卡</div>
                  <div class="time">{{ clockInTime || '未打卡' }}</div>
                </div>
                <el-button
                  v-hasPermi="['attendance:signRecord:add']"
                  v-if="!clockInStatus"
                  size="mini"
                  icon="el-icon-camera"
                  :type="clockInStatus ? 'info' : 'primary'"
                  @click="handleClock('in')"
                  :disabled="clockInStatus">
                  {{ clockInStatus ? '已打卡' : '立即打卡' }}
                </el-button>
                <dict-tag v-else :options="dict.type.sign_status" :value="signInStatus"/>
              </div>
            </el-col>

            <!-- 下班打卡 -->
            <el-col :span="12">
              <div class="punch-card" :class="{ 'punched': clockOutStatus }">
                <div class="status-icon">
                  <i :class="clockOutStatus ? 'el-icon-success' : 'el-icon-time'"/>
                </div>
                <div class="time-info">
                  <div class="label">下班打卡</div>
                  <div class="time">{{ clockOutTime || '未打卡' }}</div>
                </div>
                <el-button
                  v-hasPermi="['attendance:signRecord:add']"
                  v-if="!clockOutStatus"
                  size="mini"
                  icon="el-icon-camera"
                  :type="clockOutStatus ? 'info' : 'primary'"
                  @click="handleClock('out')"
                  :disabled="clockOutStatus"
                >
                  {{ clockOutStatus ? '已打卡' : '立即打卡' }}
                </el-button>
                <dict-tag v-else :options="dict.type.sign_status" :value="signOutStatus"/>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户账号" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="签到日期" prop="signTime">
        <el-date-picker clearable
                        v-model="queryParams.signTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择签到日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="签到状态" prop="signStatus">
        <el-select v-model="queryParams.signStatus" placeholder="请选择签到状态" clearable>
          <el-option
            v-for="dict in dict.type.sign_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">-->
      <!--  <el-button-->
      <!--    type="primary"-->
      <!--    plain-->
      <!--    icon="el-icon-plus"-->
      <!--    size="mini"-->
      <!--    @click="handleAdd"-->
      <!--    v-hasPermi="['attendance:signRecord:add']"-->
      <!--  >新增</el-button>-->
      <!--</el-col>-->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['attendance:signRecord:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['attendance:signRecord:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['attendance:signRecord:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 摄像头弹窗 -->
    <el-dialog
      title="人脸验证"
      :visible.sync="cameraDialogVisible"
      width="500px"
      @close="closeCamera"
    >
      <video ref="videoElement" class="camera-preview" autoplay playsinline></video>
      <div slot="footer" class="dialog-footer">
        <el-button @click="capturePhoto" type="primary" :loading="captureLoading">
          {{ captureLoading ? '正在验证...' : '开始验证' }}
        </el-button>
      </div>
    </el-dialog>

    <el-table v-loading="loading" :data="signRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="签到记录ID" align="center" prop="signId"/>
      <el-table-column label="用户账号" align="center" prop="userName"/>
      <el-table-column label="用户昵称" align="center" prop="nickName"/>
      <el-table-column label="手机号码" align="center" prop="phonenumber"/>
      <el-table-column label="部门名称" align="center" prop="deptName"/>
      <el-table-column label="签到时间" align="center" prop="signTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签到状态" align="center" prop="signStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sign_status" :value="scope.row.signStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['attendance:signRecord:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['attendance:signRecord:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考勤记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="签到时间" prop="signTime">
          <el-date-picker clearable
                          v-model="form.signTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择签到时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="签到状态" prop="signStatus">
          <el-select v-model="form.signStatus" placeholder="请选择签到状态">
            <el-option
              v-for="dict in dict.type.sign_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSignRecordForOwn,
  getSignRecord,
  delSignRecord,
  addSignRecord,
  updateSignRecord,
  getAttendanceStatus,
  uploadPhoto
} from "@/api/attendance/signRecord";
import {getDicts} from "@/api/system/dict/data";
import {mapGetters} from 'vuex'

export default {
  name: "SignRecord",
  dicts: ['sign_status', 'sign_field'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考勤记录表格数据
      signRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        nickName: null,
        deptName: null,
        signTime: null,
        signStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          {required: true, message: "员工ID不能为空", trigger: "blur"}
        ],
        signTime: [
          {required: true, message: "签到时间不能为空", trigger: "blur"}
        ],
        signStatus: [
          {required: true, message: "签到状态不能为空", trigger: "change"}
        ]
      },
      currentTime: '',
      clockInTime: '',
      clockOutTime: '',
      clockInStatus: false,
      clockOutStatus: false,
      signInStatus: '',
      signOutStatus: '',
      isSignIn: true,
      timer: null,
      signField: [],
      // 新增摄像头相关状态
      cameraDialogVisible: false,
      videoStream: null,
      captureLoading: false,
      faceScore: null, // 用于存储人脸识别的分数
      signType: '',
      timeString: ''
    };
  },
  mounted() {
    // 启动时间更新
    this.updateTime()
    this.timer = setInterval(() => {
      this.updateTime()
    }, 1000)
  },
  computed: {
    ...mapGetters(['avatar']),
    hasAvatar() {
      const defaultAvatar = require('@/assets/images/profile.jpg');
      return this.avatar && this.avatar !== defaultAvatar;
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.closeCamera()
  },
  created: async function () {
    // 先获取考勤状态数据
    await this.getAttendanceStatusData();
    // 再获取签到范围数据
    await this.getSignField();
    // 最后获取考勤记录列表
    this.getList();
  },
  methods: {
    // 打开摄像头
    async handleOpenCamera() {
      if (this.hasAvatar) { // 用户有个人头像
        if (!navigator.mediaDevices) {
          this.$modal.msgError('当前浏览器不支持摄像头访问');
          return;
        }
        try {
          this.videoStream = await navigator.mediaDevices.getUserMedia({
            video: {facingMode: "user"} // 前置摄像头
          })
          this.cameraDialogVisible = true
          this.$nextTick(() => {
            const video = this.$refs.videoElement
            video.srcObject = this.videoStream
          })
        } catch (error) {
          this.$modal.msgError('摄像头访问失败: ' + error.message)
        }
      } else {
        this.$modal.msgWarning('签到前必须在[个人中心]上传个人头像(证件照或者清晰面部照片)！');
      }
    },
    // 拍照并处理
    async capturePhoto() {
      try {
        this.captureLoading = true
        const video = this.$refs.videoElement
        const canvas = document.createElement('canvas')
        canvas.width = video.videoWidth
        canvas.height = video.videoHeight
        canvas.getContext('2d').drawImage(video, 0, 0)

        // 获取base64图片数据
        const photoData = canvas.toDataURL('image/jpeg', 0.8)

        // 将 base64 转换为 Blob 对象
        const blob = await this.dataURLToBlob(photoData);

        // 创建 FormData 对象
        const formData = new FormData();
        formData.append('signPhoto', blob, 'sign_photo.jpg');

        // 获取用户头像信息并转换为 Blob 对象
        // 处理为路径的情况，这里假设路径是相对路径，需要根据实际情况调整
        const img = new Image();
        img.src = this.avatar;
        await new Promise((resolve) => img.onload = resolve);
        const canvas2 = document.createElement('canvas');
        canvas2.width = img.width;
        canvas2.height = img.height;
        const ctx = canvas2.getContext('2d');
        ctx.drawImage(img, 0, 0);
        const avatarData = canvas2.toDataURL('image/jpeg');
        const avatarBlob = await this.dataURLToBlob(avatarData);
        formData.append('avatarPhoto', avatarBlob, 'avatar_photo.jpg');

        // 上传图片到服务器的逻辑
        const response = await uploadPhoto(formData);
        this.handleUploadResponse(response);

        this.closeCamera()
      } catch (error) {
        this.$modal.msgError('验证失败: ' + error.message)
        console.log('验证失败: ' + error.message);
      } finally {
        this.captureLoading = false
      }
    },
    handleUploadResponse(response) {
      if (response.error_msg && response.error_msg.toUpperCase() === 'SUCCESS') {
        // 人脸识别成功
        this.faceScore = response.result ? response.result.score : null;
        // 根据结果调用签到插入数据库
        if (this.faceScore >= 80) { // 阈值为80，大于等于80即人脸对比成功
          this.$modal.msgSuccess('人脸识别成功');
          // 插入数据库记录
          addSignRecord(this.form).then(response => {
            if(this.signType === 'in'){
              this.$message.success('上班打卡成功');
              this.clockInTime = this.timeString;
              this.clockInStatus = true;
            } else if(this.signType === 'out'){
              this.$message.success('下班打卡成功')
              this.clockOutTime = this.timeString;
              this.clockOutStatus = true;
            }
            this.getAttendanceStatusData();
            this.getList();
          })
          .catch(error => {
            // 请求失败的处理逻辑
            this.$modal.msgError(error);
          });
        } else {
          this.$modal.msgWarning('对比度：' + Math.round(this.faceScore) + ' 过低，请重试，人脸对比失败, 请保证面部无遮挡，光照正常等...');
        }
      } else {
        // 显示警告弹窗
        this.$modal.msgError('人脸对比失败：', response.error_msg);
        console.log(response.error_msg);
      }
    },
    dataURLToBlob(dataURL) {
      return new Promise((resolve) => {
        const arr = dataURL.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        resolve(new Blob([u8arr], {type: mime}));
      });
    },
    // 关闭摄像头
    closeCamera() {
      if (this.videoStream) {
        this.videoStream.getTracks().forEach(track => track.stop())
        this.videoStream = null
      }
      this.cameraDialogVisible = false
    },
    convertTimeToDate(timeStr) {
      if (!timeStr) return null;
      const [hours, minutes] = timeStr.split(':');
      const now = new Date();
      return new Date(now.getFullYear(), now.getMonth(), now.getDate(), parseInt(hours), parseInt(minutes));
    },
    updateTime() {
      const date = new Date()
      this.currentTime = date.toLocaleString('zh-CN', {
        timeZone: 'Asia/Shanghai',
        hour12: false
      })
    },
    handleClock(type) {
      const now = new Date()
      const timeString = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
      this.timeString = timeString;
      if (type === 'in') {
        const now = new Date();
        const currentHour = now.getHours();
        this.isSignIn = currentHour < 12; // 根据当前时间初始化isSignIn

        if (this.isSignIn) {
          const startTimeStr = this.getLabelByValue(0);
          const endTimeStr = this.getLabelByValue(1);

          // 将时间字符串转换为 Date 对象
          const startDate = this.convertTimeToDate(startTimeStr);
          const endDate = this.convertTimeToDate(endTimeStr);

          if (startDate && endDate) {
            if (now >= startDate) { // 可以签到
              this.signType = type;
              this.handleOpenCamera(); // 里面包括 打卡逻辑
            } else {
              this.$message.warning('当前时间不在上班签到时间范围内');
            }
          } else {
            this.$message.warning('未获取到有效的上班签到时间范围');
          }

        } else {
          this.$message.warning('当前时间无法签到')
        }

      } else {
        if (this.clockInStatus) {

          const startTimeStr = this.getLabelByValue(2);
          const endTimeStr = this.getLabelByValue(3);

          // 将时间字符串转换为 Date 对象
          const startDate = this.convertTimeToDate(startTimeStr);
          const endDate = this.convertTimeToDate(endTimeStr);
          if(startDate && endDate){
            // 发起签退，后端会进行签到状态判断
            this.signType = type;
            this.handleOpenCamera();
          } else {
            this.$message.warning('未获取到有效的下班签退时间范围');
          }
        } else {
          this.$message.warning('当天并未签到，无法签退！')
        }
      }
    },
    /** 查询考勤记录列表 */
    getList() {
      this.loading = true;
      listSignRecordForOwn(this.queryParams).then(response => {
        this.signRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    async getAttendanceStatusData() {
      return getAttendanceStatus().then(response => {
        let res = response.data;
        this.clockInTime = res.clockInTime;
        this.clockOutTime = res.clockOutTime;
        this.clockInStatus = res.clockInStatus;
        this.clockOutStatus = res.clockOutStatus;
        this.signInStatus = res.signInStatus;
        this.signOutStatus = res.signOutStatus;
      });
    },
    getSignField() {
      return getDicts("sign_field").then(response => {
        this.signField = response.data;
      });
    },
    getLabelByValue(value) {
      const item = this.signField.find(item => item.dictValue === String(value));
      return item ? item.dictLabel : '打卡时间未设置';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        signId: null,
        userId: null,
        userName: null,
        nickName: null,
        phonenumber: null,
        deptId: null,
        deptName: null,
        signTime: null,
        signStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.signId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考勤记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const signId = row.signId || this.ids
      getSignRecord(signId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考勤记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.signId != null) {
            updateSignRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSignRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const signIds = row.signId || this.ids;
      this.$modal.confirm('是否确认删除考勤记录编号为"' + signIds + '"的数据项？').then(function () {
        return delSignRecord(signIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('attendance/signRecord/export', {
        ...this.queryParams
      }, `signRecord_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>

.attendance-status {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.attendance-rule {
  font-size: 16px;
  color: #666;
  line-height: 1.5;
}

.rule-label {
  font-weight: 500;
  color: #1890ff;
}

.time-range {
  font-weight: 500;
  color: #333;
}

.work-sign {
  margin-right: 5px; /* 若不需要自动间距，直接固定间距 */
}

.spacing-area {
  margin-bottom: 30px !important; /* 基础间距 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05); /* 可选投影增强层次感 */
}

.attendance-card {
  height: 300px;
}

.time-card {
  height: 300px;
}

.time-display {
  font-size: 48px; /* 增大字体尺寸 */
  font-weight: 600; /* 加粗字体 */
  color: #2c3e50; /* 调整字体颜色 */
  font-family: 'Consolas', sans-serif;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1); /* 添加文字阴影 */
  letter-spacing: 2px; /* 增加字间距 */
  text-align: center;
  margin-top: 50px;
}

.punch-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  text-align: center;
}

.punched {
  background-color: #f6ffed;
  border-color: #b7eb8f;
}

.status-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.time-info .label {
  color: #909399;
  margin-bottom: 5px;
}

.time-info .time {
  font-size: 18px;
  color: #303133;
  margin-bottom: 10px;
}

.camera-preview {
  width: 100%;
  border-radius: 4px;
  background: #000;
}
</style>
